

import os
import sys
import time

import rpyc
from rpyc.utils import server

import dexen
from dexen.system.common import service
from dexen.system.server.core import ServerCore
from dexen.system.common.service import DexenAddr


#===============================================================================
# Globals
#===============================================================================
core = None

#===============================================================================
# The Service Class
#===============================================================================
class ServerService(dexen.Service):
    ALIASES = ["DEXEN_SERVER"]

    def on_connect(self):
        pass
    
    def on_disconnect(self):
        pass
    
    def start_job(self, schema_zip, job_name):
        schema_zip = rpyc.classic.obtain(schema_zip)
        core.start_master(schema_zip, job_name)
    
    def stop_job(self, job_id):
        core.stop_master(job_id)
    
    def del_job(self, job_id):
        core.del_master(job_id)
    
    def get_job_states(self):
        return core.get_job_states()
    
    def get_job_info(self, job_id):
        return core.get_job_state(job_id)
    
    def get_client_config_file(self, job_id):
        return core.get_client_config_file(job_id)
    
    def update(self, job_id, act_id):
        return core.get_actions(job_id, act_id)
    
    def get_ip(self):
        return service.get_my_ip()
    
    def get_archive_dir(self):
        from dexen.system.common.constants import ARCHIVE_ROOT_DIR
        return ARCHIVE_ROOT_DIR
    
def start(reg_name, is_quiet):
    global core, reg_addr
    my_ip = service.get_my_ip(service.is_local(reg_name))
    _logger = service.get_rpyc_logger("DEXEN_SERVER", is_quiet)
    srvc = server.ThreadedServer(service=ServerService, 
                                protocol_config=service.default_config,
                                auto_register=False,
                                logger=_logger)
    my_addr = DexenAddr(my_ip, srvc.port)
    reg_addr = service.get_reg_addr(reg_name)        
    conn = reg_addr.get_conn()
    conn.root.register_server(time.time(), my_addr)
    core = ServerCore(reg_addr)
    core.start()
    print "Dexen server has started successfully."
    srvc.start()     
    
#===============================================================================
# 
#===============================================================================
def main():
    pass

if __name__ == '__main__':
    main()

